# -*- coding:utf-8 -*-
# Author:Gao Xiang

import time
import paramiko
import threading
from plugin.stats import Stats


HOSTNAME = {
    'shrad000': {'host': 'xx'},
    'shard001': {'host': 'xx'},
    'shard002': {'host': 'xx'},
    'shard003': {'host': 'xx'},
    'shard004': {'host': 'xx'},
    'shard005': {'host': 'xx'},
    'shard006': {'host': 'xx'},
    'shard007': {'host': 'xx'},
    'shard008': {'host': 'xx'},
    'mongos1': {'host': 'xx'},
    'mongos2': {'host': 'xx'},
    'mongos3': {'host': 'xx'},
}

PORT = {
    'shrad000': 6677,
    'shard001': 6677,
    'shard002': 6677,
    'shard003': 6677,
    'shard004': 6677,
    'shard005': 6677,
    'shard006': 6677,
    'shard007': 6677,
    'shard008': 6677,
    'mongos1': 6677,
    'mongos2': 6677,
    'mongos3': 6677,
}


class SSH(object):

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.username = 'xiang.gao'
        self.ssh = paramiko.SSHClient()

    def connect(self):
        private_key = paramiko.RSAKey.from_private_key_file('/Users/gaox/.ssh/id_rsa')
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(hostname=self.host, port=self.port, username=self.username, pkey=private_key)

    def cmd(self, comd):
        stdin, stdout, stderr = self.ssh.exec_command(comd)
        return stdin, stdout, stderr

    def cpu_load(self):
        comd = 'uptime'
        stdin, stdout, stderr = self.cmd(comd)
        if not stdout:
            return
        result = stdout.read().decode()
        # print(result)
        load_average = result.split(', ')[-3]
        # print(load_average)
        load_name = load_average.split(':')[0].strip()
        load_val = load_average.split(':')[-1].strip()
        return load_name, float(load_val)

    def mem_free(self):
        comd = 'cat /proc/meminfo|grep MemAvailable'
        stdin, stdout, stderr = self.cmd(comd)
        if not stdout:
            return
        result = stdout.read().decode()
        # print(result)
        mem_name = result.split(':')[0].strip()
        mem_str = result.split(':')[1]
        mem_kb = mem_str.split()[0].strip()
        mem_gb = int(mem_kb) / 1024 / 1024
        mem_val = round(mem_gb, 2)  # 取小数点后两位
        return mem_name, mem_val


# 发送数据到statsd服务端
def client(hostname, host, port, method):
    """
    :param hostname: 主机名,shardxxx
    :param host: 主机的IP地址
    :param port: 主机ssh端口
    :param method: 调用的函数,有cpu_load和mem_free两种
    :return:
    """
    hostname = hostname
    host = host
    port = port
    method = method
    conn = SSH(host, port)
    conn.connect()
    while True:
        # name, val = conn.cpu_load()
        name, val = getattr(conn, method)()
        # print(load_name, load_val)
        stat_client = Stats(name)
        stat_client.connect()
        stat_client.send_data(hostname, val)
        print(hostname, val, 'done')
        time.sleep(10)


# 多线程执行
def threads():
    cpu_shards = []
    mem_frees = []
    for i in HOSTNAME:
        HOSTNAME[i]['port'] = PORT[i]
        HOSTNAME[i]['method'] = 'cpu_load'
        # print(i, HOSTNAME[i]['host'], HOSTNAME[i]['port'], HOSTNAME[i]['method'])
        cpu_shards.append(threading.Thread(target=client,
                                           args=(i, HOSTNAME[i]['host'], HOSTNAME[i]['port'], HOSTNAME[i]['method'])))
        HOSTNAME[i]['method'] = 'mem_free'
        # print(i, HOSTNAME[i]['host'], HOSTNAME[i]['port'], HOSTNAME[i]['method'])
        mem_frees.append(threading.Thread(target=client,
                                          args=(i, HOSTNAME[i]['host'], HOSTNAME[i]['port'], HOSTNAME[i]['method'])))
    for c in cpu_shards:
        c.start()
    for m in mem_frees:
        m.start()


if __name__ == '__main__':
    threads()